package org.javason;

import java.io.StringWriter;

import junit.framework.TestCase;

import org.apache.log4j.Logger;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.SimpleLayout;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import org.javason.jsonrpc.JsonRpcClient;
import org.javason.util.Metrics;
import org.javason.util.MetricsConfiguration;

public class TestMetrics extends TestCase {
	
	public void testMetricsSupport() {
		(new MetricsConfiguration()).setGlobalMinThreshold(0.0);
		Logger.getLogger(Metrics.class).removeAllAppenders();
		
		StringWriter strWriter = new StringWriter();
		Logger.getLogger(Metrics.class).addAppender(new WriterAppender(new SimpleLayout(), strWriter));
		
		Metrics metrics = Metrics.beginCollection();
		metrics.endAndLogCollection();
		System.out.println("APPENDER: " + strWriter.toString());
		//assertEquals("ERROR - [METRICS] org.javason.TestMetrics testMetricsSupport | 0.0", strWriter.toString().trim());
		
		strWriter.getBuffer().delete(0, strWriter.getBuffer().length());
		Metrics metrics2 = Metrics.beginCollection();
		metrics2.endAndLogCollection("%s", "HERE");
		System.out.println("APPENDER: " + strWriter.toString());
		//assertEquals("ERROR - [METRICS] HERE | 0.0", strWriter.toString().trim());

		strWriter.getBuffer().delete(0, strWriter.getBuffer().length());
		Metrics metrics3 = Metrics.beginCollection();
		Metrics metrics4 = Metrics.beginCollection();
		metrics4.endAndLogCollection("%s", "EMBEDDED 2");
		metrics3.endAndLogCollection("%s", "EMBEDDED 1");
		String[] ids = strWriter.getBuffer().toString().split("\\|");
		assertEquals(Integer.parseInt(ids[1].replaceAll("\\[|\\]", "")), Integer.parseInt(ids[4].replaceAll("\\[|\\]", "")));
		
		System.out.println("APPENDER: " + strWriter.toString());
		
		strWriter.getBuffer().delete(0, strWriter.getBuffer().length());
		try {
			ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("com/rhg/service/test_metrics.xml");
			JsonInterface2 testor = (JsonInterface2) context.getBean("testBean");
			testor.blah("BLAH!");
		
			System.out.println("APPENDER: " + strWriter.toString());

			assertTrue(-1 != strWriter.toString().indexOf("arguments"));
		} catch (Exception exp) {
			exp.printStackTrace();
		}
		
		
		
		// no args
		
		strWriter.getBuffer().delete(0, strWriter.getBuffer().length());
		try {
			ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("com/rhg/service/test_metrics.xml");
			JsonInterface2 testor = (JsonInterface2) context.getBean("testBean2");
			testor.blah("BLAH!");
		
			System.out.println("APPENDER: " + strWriter.toString());
			assertEquals(-1, strWriter.toString().indexOf("arguments"));
			
		} catch (Exception exp) {
			exp.printStackTrace();
		}
		
		
	}
	
	
}
